package org.yray.sip.time;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.yray.sip.base.MsgType;
import org.yray.sip.constant.Constants;
import org.yray.sip.constant.MediaCodeEnum;
import org.yray.sip.constant.SessionStatusEnum;
import org.yray.sip.creator.MessageCreator;
import org.yray.sip.log.AbstractLog;
import org.yray.sip.packet.SendNotifyPacket;
import org.yray.sip.rtp.sender.ISipSessionCache;
import org.yray.sip.server.SipSession;
import org.yray.sip.utils.IcspBeanHolder;

import java.util.Optional;

@Data
@Slf4j
public class WaitTimeOutTask extends BaseSendTask {

    private String callId;

    public WaitTimeOutTask(long time, String callId)
    {
        this.time=time;
        this.callId=callId;

    }
    @Override
    public void doJob() {
        SipSession session= IcspBeanHolder.getBean(ISipSessionCache.class).get(callId);
        if(session==null) {
            return;
        }
        AbstractLog.log(callId,"WaitTimeOutTask","进入超时status={}",session.getStatus());
        if(session.getStatus().get()== SessionStatusEnum.TO_MAN_RING
        ||session.getStatus().get()== SessionStatusEnum.TO_MAN_ING)
        {
            //通知转人工失败
            SendNotifyPacket packet=new SendNotifyPacket(session.getCallId(), MediaCodeEnum.TOMAN_FAIL.name(), Constants.MUSIC_PLAY_FINISH,null);

            //判断session.getToManWaitId()这主要针对的是第三方一直没有空闲座席的情况
            Optional.ofNullable(session.getToManWaitId()).ifPresent(manWaitId->{
                SipSession toManWaitSipSession = IcspBeanHolder.getBean(ISipSessionCache.class).get(manWaitId);
                //判断toManWaitSipSession,这主要针对分机振铃一直不接的情况，对于座席侧的进行取消
                Optional.ofNullable(toManWaitSipSession).ifPresent(v -> {
                    AbstractLog.log(callId,"WaitTimeOutTask","人工座席还在振铃中，toManWaitSipSession={}",toManWaitSipSession.getStatus());
                    String msg = MessageCreator.getCreator(MsgType.CANCEL).createMsg(v);
                    getSipServerHandler().sendToSipServer(session,msg);
                });
            });


        }
    }
}
